// 自定义tabbar组件
Component({
  data: {
    selected: 0,
    showTabbar: false,
    list: [
      {
        pagePath: "/pages/index/index",
        text: "首页",
        iconPath: "/images/home.png",
        selectedIconPath: "/images/home-active.png"
      },
      {
        pagePath: "/pages/room/room", 
        text: "房间",
        iconPath: "/images/room.png",
        selectedIconPath: "/images/room-active.png"
      },
      {
        pagePath: "/pages/profile/profile",
        text: "我的", 
        iconPath: "/images/profile.png",
        selectedIconPath: "/images/profile-active.png"
      }
    ]
  },

  attached() {
    // 检查是否有房间，决定是否显示tabbar
    this.checkRoomStatus()
    // 设置当前选中的页面
    this.setCurrentPage()
  },

  ready() {
    // 组件准备就绪后再次设置选中状态
    this.setCurrentPage()
  },

  methods: {
    // 检查房间状态
    checkRoomStatus() {
      const RoomCache = require('../../utils/roomCache')
      const roomData = RoomCache.getRoomBasicInfo()
      
      if (roomData) {
        // 有房间，显示tabbar
        this.setData({
          showTabbar: true
        })
      } else {
        // 没有房间，隐藏tabbar
        this.setData({
          showTabbar: false
        })
      }
    },

    // 切换tab
    switchTab(e) {
      console.log('switchTab被调用', e)
      
      const data = e.currentTarget.dataset
      const url = data.path
      const index = data.index
      
      console.log('点击tabbar:', url, index)
      
      // 更新选中状态
      this.setData({
        selected: index
      })
      
      // 使用redirectTo替换当前页面，避免页面栈溢出
      wx.redirectTo({ 
        url,
        success: () => {
          console.log('页面跳转成功，当前选中:', index)
        },
        fail: (err) => {
          console.error('页面跳转失败:', err)
        }
      })
    },

    // 更新tabbar显示状态（供外部调用）
    updateTabbarStatus(hasRoom) {
      this.setData({
        showTabbar: hasRoom
      })
    },

    // 设置当前选中的页面（供外部调用）
    setCurrentPage() {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const route = currentPage.route
      
      let selectedIndex = 0
      if (route.includes('pages/index/index')) {
        selectedIndex = 0
      } else if (route.includes('pages/room/room')) {
        selectedIndex = 1
      } else if (route.includes('pages/profile/profile')) {
        selectedIndex = 2
      }
      
      console.log('设置tabbar选中状态:', route, selectedIndex, '当前selected:', this.data.selected)
      
      // 强制更新选中状态
      this.setData({
        selected: selectedIndex
      })
      console.log('tabbar选中状态已更新为:', selectedIndex)
    }
  }
})